#include <stdio.h>
#include <stdlib.h>
#include "slist.h"


// frist static function to create a new node
// only use in this file
static sNode_t *newNode(int x) {
    sNode_t *node = (sNode_t *)malloc(sizeof(sNode_t));
    if (node != NULL) {
        node->data = x;
        node->next = NULL;
    }
    return node;
}


//insert x after prevNode
void insertAfter(sNode_t *prevNode, int x) {
    sNode_t *node = newNode(x);
    if (!node) return;
    if (prevNode == NULL) {
        prevNode = node;
        node->next = prevNode;
    } else {
        node->next = prevNode->next;
        prevNode->next = node;
    }
}

//insert x at front
void insertAtFront(sNode_t **head, int x) {
    sNode_t *node = newNode(x);
    if (!node) return;

    if ( !*head ) { //head==NULL
        *head = node;
        node->next = *head;
    } else {
        sNode_t *tailNode = *head;
        while(tailNode->next != *head) 
            tailNode = tailNode->next;
        node->next = *head;
        tailNode->next = node; 
        *head = node;
    }
} 


//insert node at tail
void insertAtTail(sNode_t **head, int x) {
    sNode_t *node = newNode(x);
    if (!node) return;

    if (!*head) {//head == NULL
        *head = node;
        node->next = *head;
    } else {
        sNode_t *tailNode = *head;
        while(tailNode->next != *head) 
            tailNode = tailNode->next;
        node->next = tailNode->next;
        tailNode->next = node; 
    }
}

//delete a node from front
sNode_t * deleteFromFront(sNode_t **head){
    if (!*head) return NULL;

    sNode_t *frontNode = *head;
    if (frontNode->next == *head) //only one node in list
        *head = NULL;
    else {
        sNode_t * tailNode = *head;
        while(tailNode->next != *head) 
            tailNode = tailNode->next;
        tailNode->next = (*head)->next;
        *head = (*head)->next; 
    }
    frontNode->next = NULL;
    return frontNode;
}

void printList(sNode_t *head) {
    sNode_t *ptrNode = head;

    if (!head) {
        printf("list is empty\n");
        return;
    }
    while(ptrNode->next != head) {
        printf("%d ", ptrNode->data);
        ptrNode = ptrNode->next;
    }
    printf("%d\n", ptrNode->data);
}
